package com.gewu.pm.ui.activity.filter;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.blankj.utilcode.util.LogUtils;
import com.gewu.pm.R;
import com.gewu.pm.app.AppActivity;
import com.gewu.pm.ui.adapter.FilterTagAdapter;
import com.gewu.pm.ui.adapter.FilterTimeAdapter;
import com.gewu.pm.ui.dialog.DateDialog;
import com.gewu.pm.ui.dialog.SelectHandlingPersonDialog;
import com.gewu.pm.ui.dialog.SelectSalesRegionDialog;
import com.gewu.pm.ui.dialog.SelectSubmitterDialog;
import com.gewu.pm.utils.MoneyInputHelper;
import com.hjq.base.BaseAdapter;
import com.hjq.base.BaseDialog;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 筛选页面
 */
public final class OldFilterActivity extends AppActivity implements BaseAdapter.OnItemClickListener {

    private static final String TAG = "FilterActivity";

    /**
     * 销售区域
     */
    private TextView tvSalesArea;

    /**
     * 提交时间
     */
    private RecyclerView rvTime;
    private FilterTimeAdapter timeAdapter;
    private LinearLayout llStartTime;
    private TextView tvStartTime;
    private LinearLayout llEndTime;
    private TextView tvEndTime;

    /**
     * 经办人
     */
    private TextView tvManager;

    /**
     * 收款方式
     */
    private RecyclerView rvPaymentMethod;
    private FilterTagAdapter paymentMethodAdapter;

    /**
     * 收款金额
     */
    private EditText etMinAmount;
    private EditText etMaxAmount;

    /**
     * 提交人
     */
    private TextView tvSubmitter;

    /**
     * 单据类型
     */
    private RecyclerView rvDocumentType;
    private FilterTagAdapter documentTypeAdapter;

    /**
     * 付款类型
     */
    private RecyclerView rvPaymentType;
    private FilterTagAdapter paymentTypeAdapter;

    /**
     * 底部按钮
     */
    private TextView tvReset;
    private TextView tvConfirm;

    /**
     * 时间选项列表
     */
    private List<String> timeOptions;
    /**
     * 收款方式选项列表
     */
    private List<String> paymentMethodOptions;
    /**
     * 单据类型选项列表
     */
    private List<String> documentTypeOptions;
    /**
     * 付款类型选项列表
     */
    private List<String> paymentTypeOptions;

    public static void start(Context context) {
        Intent intent = new Intent(context, OldFilterActivity.class);
        context.startActivity(intent);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.filter_activity;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        // 销售区域
        tvSalesArea = findViewById(R.id.tv_sales_area);

        // 提交时间
        rvTime = findViewById(R.id.rv_time);
        llStartTime = findViewById(R.id.ll_start_time);
        tvStartTime = findViewById(R.id.tv_start_time);
        llEndTime = findViewById(R.id.ll_end_time);
        tvEndTime = findViewById(R.id.tv_end_time);

        // 经办人
        tvManager = findViewById(R.id.tv_manager);

        // 收款方式
        rvPaymentMethod = findViewById(R.id.rv_payment_method);

        // 收款金额
        etMinAmount = findViewById(R.id.et_min_amount);
        etMaxAmount = findViewById(R.id.et_max_amount);

        // 提交人
        tvSubmitter = findViewById(R.id.tv_submitter);

        // 单据类型
        rvDocumentType = findViewById(R.id.rv_document_type);

        // 付款类型
        rvPaymentType = findViewById(R.id.rv_payment_type);

        // 底部按钮
        tvReset = findViewById(R.id.tv_reset);
        tvConfirm = findViewById(R.id.tv_confirm);

        // 设置RecyclerView
        setupTimeRecyclerView();
        setupPaymentMethodRecyclerView();
        setupDocumentTypeRecyclerView();
        setupPaymentTypeRecyclerView();

        // 设置金额输入限制（最多2位小数）
        setupAmountInputLimit();

        // 设置点击事件
        setOnClickListener(
                tvSalesArea, llStartTime, llEndTime, tvManager, tvSubmitter,
                tvReset, tvConfirm);
    }

    @Override
    protected void initData() {
        // 初始化提交时间选项
        timeOptions = Arrays.asList(
                "今日",
                "昨日",
                "本周",
                "本月",
                "近7天",
                "近30天",
                "近90天",
                "自定义"
        );
        timeAdapter.setData(timeOptions);

        // 初始化收款方式选项
        paymentMethodOptions = Arrays.asList(
                "微信",
                "支付宝",
                "电汇",
                "钱包余额"
        );
        paymentMethodAdapter.setData(paymentMethodOptions);

        // 初始化单据类型选项
        documentTypeOptions = Arrays.asList(
                "收款",
                "退款"
        );
        documentTypeAdapter.setData(documentTypeOptions);

        // 初始化付款类型选项
        paymentTypeOptions = Arrays.asList(
                "全部",
                "终端付款",
                "代支付"
        );
        paymentTypeAdapter.setData(paymentTypeOptions);
    }

    @Override
    public void onClick(View view) {
        int viewId = view.getId();
        if (viewId == R.id.tv_sales_area) {
            // 点击销售区域，弹出选择对话框
            new SelectSalesRegionDialog.Builder(this)
                    .setDefaultRegion(tvSalesArea.getText().toString())
                    .setListener(new SelectSalesRegionDialog.OnListener() {
                        @Override
                        public void onSelected(BaseDialog dialog, String region) {
                            // 显示选中的区域
                            tvSalesArea.setText(region);
                            tvSalesArea.setTextColor(getResources().getColor(R.color.cb3));
                        }

                        @Override
                        public void onCancel(BaseDialog dialog) {
                            // 取消选择
                        }
                    })
                    .show();

        } else if (viewId == R.id.ll_start_time) {// 点击开始时间
            // TODO: 打开日期选择器
            // 日期选择对话框
            new DateDialog.Builder(this)
                    .setTitle(getString(R.string.date_title))
                    // 确定按钮文本
                    .setConfirm(getString(R.string.common_confirm))
                    // 设置 null 表示不显示取消按钮
                    .setCancel(getString(R.string.common_cancel))
                    // 设置日期
                    //.setDate("2018-12-31")
                    //.setDate("20181231")
                    //.setDate(1546263036137)
                    // 设置年份
                    //.setYear(2018)
                    // 设置月份
                    //.setMonth(2)
                    // 设置天数
                    //.setDay(20)
                    // 不选择天数
                    //.setIgnoreDay()
                    .setListener(new DateDialog.OnListener() {
                        @Override
                        public void onSelected(BaseDialog dialog, int year, int month, int day) {
                            String time = year + getString(R.string.common_year) + month + getString(R.string.common_month) + day + getString(R.string.common_day);
                            toast(time);
                            tvStartTime.setText(time);
                            // 如果不指定时分秒则默认为现在的时间
 /*                           Calendar calendar = Calendar.getInstance();
                            calendar.set(Calendar.YEAR, year);
                            // 月份从零开始，所以需要减 1
                            calendar.set(Calendar.MONTH, month - 1);
                            calendar.set(Calendar.DAY_OF_MONTH, day);
                            toast("时间戳：" + calendar.getTimeInMillis());*/

                            //toast(new SimpleDateFormat("yyyy年MM月dd日 kk:mm:ss").format(calendar.getTime()));
                        }

                        @Override
                        public void onCancel(BaseDialog dialog) {
                            toast("取消了");
                        }
                    })
                    .show();

        } else if (viewId == R.id.ll_end_time) {// 点击结束时间
            // TODO: 打开日期选择器
            // 日期选择对话框
            new DateDialog.Builder(this)
                    .setTitle(getString(R.string.date_title))
                    // 确定按钮文本
                    .setConfirm(getString(R.string.common_confirm))
                    // 设置 null 表示不显示取消按钮
                    .setCancel(getString(R.string.common_cancel))
                    .setListener(new DateDialog.OnListener() {
                        @Override
                        public void onSelected(BaseDialog dialog, int year, int month, int day) {
                            String time = year + getString(R.string.common_year) + month + getString(R.string.common_month) + day + getString(R.string.common_day);
                            toast(time);
                            tvEndTime.setText(time);
                        }
                    })
                    .show();

        } else if (viewId == R.id.tv_manager) {
            // 点击经办人，弹出选择对话框
            new SelectHandlingPersonDialog.Builder(this)
                    .setDefaultPerson(tvManager.getText().toString())
                    .setListener(new SelectHandlingPersonDialog.OnListener() {
                        @Override
                        public void onSelected(BaseDialog dialog, String personName) {
                            // 显示选中的经办人
                            tvManager.setText(personName);
                            tvManager.setTextColor(getResources().getColor(R.color.cb3));
                        }

                        @Override
                        public void onCancel(BaseDialog dialog) {
                            // 取消选择
                        }
                    })
                    .show();

        } else if (viewId == R.id.tv_submitter) {// 点击提交人，弹出选择对话框
            new SelectSubmitterDialog.Builder(this,1)
                    .setListener(new SelectSubmitterDialog.OnListener() {
                        @Override
                        public void onSelected(BaseDialog dialog, String submitter, int type, Object data) {
                            // 显示选中的提交人
                            tvSubmitter.setText(submitter);
                            tvSubmitter.setTextColor(getResources().getColor(R.color.cb3));
                        }

                        @Override
                        public void onCancel(BaseDialog dialog) {
                            // 取消选择
                        }
                    })
                    .show();

        } else if (viewId == R.id.tv_reset) {
            // 点击重置按钮
            resetAllSelections();

        } else if (viewId == R.id.tv_confirm) {
            // 点击确定按钮
            confirmFilter();
        }
    }

    /**
     * 设置提交时间RecyclerView
     */
    private void setupTimeRecyclerView() {
        // 设置网格布局，3列
        GridLayoutManager layoutManager = new GridLayoutManager(this, 3);
        rvTime.setLayoutManager(layoutManager);

        // 设置适配器
        timeAdapter = new FilterTimeAdapter(this);
        timeAdapter.setOnItemClickListener(this);
        rvTime.setAdapter(timeAdapter);
    }

    /**
     * 设置收款方式RecyclerView
     */
    private void setupPaymentMethodRecyclerView() {
        // 设置网格布局，3列
        GridLayoutManager layoutManager = new GridLayoutManager(this, 3);
        rvPaymentMethod.setLayoutManager(layoutManager);

        // 设置适配器
        paymentMethodAdapter = new FilterTagAdapter(this);
        paymentMethodAdapter.setOnItemClickListener(this);
        rvPaymentMethod.setAdapter(paymentMethodAdapter);
    }

    /**
     * 设置单据类型RecyclerView
     */
    private void setupDocumentTypeRecyclerView() {
        // 设置网格布局，2列
        GridLayoutManager layoutManager = new GridLayoutManager(this, 2);
        rvDocumentType.setLayoutManager(layoutManager);

        // 设置适配器
        documentTypeAdapter = new FilterTagAdapter(this);
        documentTypeAdapter.setOnItemClickListener(this);
        rvDocumentType.setAdapter(documentTypeAdapter);
    }

    /**
     * 设置付款类型RecyclerView
     */
    private void setupPaymentTypeRecyclerView() {
        // 设置网格布局，3列
        GridLayoutManager layoutManager = new GridLayoutManager(this, 3);
        rvPaymentType.setLayoutManager(layoutManager);

        // 设置适配器
        paymentTypeAdapter = new FilterTagAdapter(this);
        paymentTypeAdapter.setOnItemClickListener(this);
        rvPaymentType.setAdapter(paymentTypeAdapter);
    }

    /**
     * 设置金额输入限制（最多2位小数）
     */
    private void setupAmountInputLimit() {
        // 为最小金额输入框设置限制
        MoneyInputHelper.setMoneyInput(etMinAmount);
        // 为最大金额输入框设置限制
        MoneyInputHelper.setMoneyInput(etMaxAmount);
    }

    /**
     * 重置所有选择
     */
    private void resetAllSelections() {
        // 重置销售区域
        tvSalesArea.setText(R.string.please_select_sales_area);
        tvSalesArea.setTextColor(getResources().getColor(R.color.cb9));

        // 重置提交时间
        timeAdapter.clearSelection();

        // 重置开始/结束时间
        tvStartTime.setText(R.string.start_time);
        tvStartTime.setTextColor(getResources().getColor(R.color.cb9));
        tvEndTime.setText(R.string.end_time);
        tvEndTime.setTextColor(getResources().getColor(R.color.cb9));

        // 重置经办人
        tvManager.setText(R.string.please_select_manager);
        tvManager.setTextColor(getResources().getColor(R.color.cb9));

        // 重置收款方式
        paymentMethodAdapter.clearSelection();

        // 重置收款金额
        etMinAmount.setText("");
        etMaxAmount.setText("");

        // 重置提交人
        tvSubmitter.setText(R.string.please_select_submitter);
        tvSubmitter.setTextColor(getResources().getColor(R.color.cb9));

        // 重置单据类型
        documentTypeAdapter.clearSelection();

        // 重置付款类型
        paymentTypeAdapter.clearSelection();

        toast("已重置");
    }

    /**
     * 确定筛选，打印所有选中的内容
     */
    private void confirmFilter() {
        List<String> selectedItems = new ArrayList<>();

        // 销售区域
        String salesArea = tvSalesArea.getText().toString();
        if (!salesArea.equals(getString(R.string.please_select_sales_area))) {
            selectedItems.add("销售区域: " + salesArea);
        }

        // 提交时间
        String selectedTime = timeAdapter.getSelectedText();
        if (!selectedTime.isEmpty()) {
            selectedItems.add("提交时间: " + selectedTime);
        }

        // 开始时间
        String startTime = tvStartTime.getText().toString();
        if (!startTime.equals(getString(R.string.start_time))) {
            selectedItems.add("开始时间: " + startTime);
        }

        // 结束时间
        String endTime = tvEndTime.getText().toString();
        if (!endTime.equals(getString(R.string.end_time))) {
            selectedItems.add("结束时间: " + endTime);
        }

        // 经办人
        String manager = tvManager.getText().toString();
        if (!manager.equals(getString(R.string.please_select_manager))) {
            selectedItems.add("经办人: " + manager);
        }

        // 收款方式
        String paymentMethod = paymentMethodAdapter.getSelectedText();
        if (!paymentMethod.isEmpty()) {
            selectedItems.add("收款方式: " + paymentMethod);
        }

        // 收款金额
        String minAmount = etMinAmount.getText().toString().trim();
        String maxAmount = etMaxAmount.getText().toString().trim();
        if (!minAmount.isEmpty() || !maxAmount.isEmpty()) {
            selectedItems.add("收款金额: " + minAmount + " - " + maxAmount);
        }

        // 提交人
        String submitter = tvSubmitter.getText().toString();
        if (!submitter.equals(getString(R.string.please_select_submitter))) {
            selectedItems.add("提交人: " + submitter);
        }

        // 单据类型
        String documentType = documentTypeAdapter.getSelectedText();
        if (!documentType.isEmpty()) {
            selectedItems.add("单据类型: " + documentType);
        }

        // 付款类型
        String paymentType = paymentTypeAdapter.getSelectedText();
        if (!paymentType.isEmpty()) {
            selectedItems.add("付款类型: " + paymentType);
        }

        // 打印所有选中的内容
        LogUtils.d(TAG, "========== 筛选条件 ==========");
        if (selectedItems.isEmpty()) {
            LogUtils.d(TAG, "未选择任何筛选条件");
        } else {
            for (String item : selectedItems) {
                LogUtils.d(TAG, item);
            }
        }
        LogUtils.d(TAG, "==============================");

        // 提示用户
        if (selectedItems.isEmpty()) {
            toast("未选择任何筛选条件");
        } else {
            toast("已确定筛选，详情请查看日志");
            // TODO: 将筛选条件返回给上一个页面或执行筛选操作
        }
    }

    /**
     * {@link BaseAdapter.OnItemClickListener}
     */
    @Override
    public void onItemClick(RecyclerView recyclerView, View itemView, int position) {
        int viewId = recyclerView.getId();

        if (viewId == R.id.rv_time) {
            // 提交时间点击
            timeAdapter.setSelectedPosition(position);
            // 移除 Toast 提示，让点击反馈更流畅
            // 用户可以通过视觉效果（红色边框）直接看到选中状态

        } else if (viewId == R.id.rv_payment_method) {
            // 收款方式点击
            paymentMethodAdapter.setSelectedPosition(position);
            // 移除 Toast 提示，让点击反馈更流畅

        } else if (viewId == R.id.rv_document_type) {
            // 单据类型点击
            documentTypeAdapter.setSelectedPosition(position);
            // 移除 Toast 提示，让点击反馈更流畅

        } else if (viewId == R.id.rv_payment_type) {
            // 付款类型点击
            paymentTypeAdapter.setSelectedPosition(position);
            // 移除 Toast 提示，让点击反馈更流畅
        }
    }
}
